package com.fishery.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fishery.entity.GlobalException;
import com.fishery.entity.StatusCode;
import com.fishery.order.entity.Customer;
import com.fishery.order.entity.vo.CustomerRankVo;
import com.fishery.order.entity.vo.CustomerVo;
import com.fishery.order.mapper.CustomerMapper;
import com.fishery.order.service.CustomerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 顾客服务实现类
 * </p>
 *
 * @author run 、 ghost
 * @since 2021-01-31
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {

	@Autowired
	private CustomerMapper customerMapper;

	@Override
	public boolean createCustomer(Customer customer) {
		if (customer.getCustomerType() == null
				|| customer.getCustomerType() <= 0
				|| customer.getCustomerType() > 2) {
			throw new GlobalException(StatusCode.ERROR, "客户类型不合法");
		}
		return customerMapper.insert(customer) > 0;
	}

	@Override
	public boolean updateCustomerInfo(CustomerVo customerVo) {
		try {
			return customerMapper.updateById(customerVo) > 0;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public boolean deleteCustomer(String customerId) {
		return customerMapper.deleteById(customerId) > 0;
	}

	@Override
	public List<CustomerVo> searchCustomerOfBase(String baseId) {
		return customerMapper.findCustomerVos(baseId);
	}

	@Override
	public IPage<CustomerVo> searchCustomerOfBase(String baseId, Integer page, Integer size) {
		if (page <= 0) {
			page = 1;
		}
		if (size <= 0) {
			size = 5;
		}
		Page<CustomerVo> pageInfo = new Page<>(page, size);
		List<CustomerVo> records = customerMapper.selectCustomerVosWithPage(baseId, (page - 1) * size, size);
		QueryWrapper wrapper = new QueryWrapper();
		wrapper.eq("base_id", baseId);
		int total = customerMapper.selectCount(wrapper);
		pageInfo.setRecords(records);
		pageInfo.setTotal(total);
		pageInfo.setPages(total / size + (total % size == 0 ? 0 : 1));
		return pageInfo;
	}

	@Override
	public List<CustomerRankVo> getTopCustomerOfBase(String baseId, Integer size) {
		return customerMapper.findTopCustomerOfBase(baseId,size);
	}
}
